package com.ls.utils;

import com.ls.constant.SystemConstants;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

/**
 * @ClassName DateTimeUtils
 * @Description 时间工具类
 * @Author TangQuanBin
 * @Date 2019/9/17 16:05
 * @Version 1.0
 **/
public class DateTimeUtil {

    public static final String DEFAULT_FORMAT_DATE = "yyyy-MM-dd HH:mm:ss";
    public static final String FORMAT_YMD = "yyyy-MM-dd";
    public static final String FORMAT_DATE_SFTP = "yyyy_MM_dd_HH_mm_ss";
    public static final String FORMAT_DATE_SSS = "yyyy-MM-dd HH:mm:ss.SSS";
    public static final String FORMAT_DATE_yyyyMMddHHmm = "yyyy-MM-dd HH:mm";
    public static final String FORMAT_YM = "yyyyMM";

    public static final String FORMAT_HH = "yyyyMMddHH";
    public static final String FORMAT_SMS = "yyyyMMddHHmmss";
    public static final String FORMAT_SN = "yyyyMMddHHmmssSSS";

    /**
     * 获取当前时间
     *
     * @return
     */
    public static Timestamp now() {
        return new Timestamp(System.currentTimeMillis());
    }

    public static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    /**
     * @param format "yyyy-MM-dd HH:mm:ss:SSS"或"yyyy-MM-dd HH:mm:ss"。
     * @return 返回文本信息的日期对应的格林威治标准时间（1970年1月1日00:00:00.000）的偏移量,单位是毫秒。 1秒=1000毫秒。
     */
    public static long dateTimeParse(String datetime, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        try {
            Date date = sdf.parse(datetime);
            return date.getTime();
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
        return 0;
    }

    /**
     * date转string
     *
     * @param date      Date
     * @param formatStr 格式
     * @return
     */
    public static String formatDateToString(Date date, String formatStr) {
        return (new SimpleDateFormat((formatStr == null ? DEFAULT_FORMAT_DATE
                : formatStr))).format(date);
    }

    /**
     * LocalDateTime转string
     *
     * @param localDateTime
     * @return
     */
    public static String formatLocalDateTimeToString(LocalDateTime localDateTime) {
        return localDateTime.format(DateTimeFormatter.ofPattern(DEFAULT_FORMAT_DATE));
    }


    public static String formatToString(LocalDateTime localDateTime, String format) {
        return localDateTime.format(DateTimeFormatter.ofPattern(format));
    }

    /**
     * string转date
     *
     * @param dateStr   时间字符串
     * @param formatStr 格式
     * @return
     */
    public static Date formatStringToDate(String dateStr, String formatStr) throws ParseException {
        return (new SimpleDateFormat((formatStr == null ? DEFAULT_FORMAT_DATE
                : formatStr))).parse(dateStr);
    }

    /**
     * 比较两个时间，如果endtime晚于begintime，则返回true，否则返回false
     *
     * @param beginTime
     * @param endTime
     * @return
     */
    public static boolean beginTimeisBeforeEndTime(String beginTime, String endTime) {
        long begin = dateTimeParse(beginTime, DEFAULT_FORMAT_DATE);
        long end = dateTimeParse(endTime, DEFAULT_FORMAT_DATE);
        return end > begin;
    }

    public static boolean beginTimeisBeforeEndTime(Date beginTime, Date endTime) {
        long begin = beginTime.getTime();
        long end = endTime.getTime();
        return end > begin;
    }

    /**
     * string转date加日期
     *
     * @param dateStr 时间字符串
     * @param daynum  天数
     * @return
     */
    public static Date formatStringToDateAddDay(String dateStr, Integer daynum) throws ParseException {
        if (dateStr.length() <= SystemConstants.DATE_LENGTH) {
            dateStr = dateStr + " 00:00:00";
        } else {
            return (new SimpleDateFormat(DEFAULT_FORMAT_DATE)).parse(dateStr);
        }
        SimpleDateFormat sdf = new SimpleDateFormat(DEFAULT_FORMAT_DATE);
        Calendar calendar = new GregorianCalendar();
        Date date = sdf.parse(dateStr);
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, daynum);
        return calendar.getTime();
    }

    public static Date formatStringToDateTime(String dateStr, String formatStr) throws ParseException {
        if (dateStr.length() <= SystemConstants.DATE_LENGTH) {
            dateStr = dateStr + " 00:00:00";
        }
        return (new SimpleDateFormat((formatStr == null ? DEFAULT_FORMAT_DATE
                : formatStr))).parse(dateStr);
    }

    public static LocalDateTime formatStringToLocalDateTime(String dateStr, String formatStr) throws ParseException {
        LocalDateTime localDateTime = LocalDateTime.parse(dateStr, (formatStr == null ? DATE_TIME_FORMATTER : DateTimeFormatter.ofPattern(formatStr)));
        return localDateTime;
    }


    public static LocalTime String2LocalTime(String str) {
//        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        try {
            DateTimeFormatter fmt = DateTimeFormatter.ofPattern("HH:mm:ss");
            return LocalTime.parse(str, fmt);
        } catch (Exception e) {
            return null;
        }
    }

    public static LocalDate String2LocalDate(String str) {
        try {
            DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            return LocalDate.parse(str, fmt);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取某个时间是一天中第N个XX分钟，这里XX为15
     */
    public static String getminuteTimes(LocalDateTime localDateTime) {
        if (localDateTime == null) {
            localDateTime = LocalDateTime.now();
        }
        int hour = localDateTime.getHour();
        int minute = localDateTime.getMinute();
        int result = (hour * 60 + minute) / 15;
        return String.valueOf(result);
    }


    /**
     * 把时间转成年月
     */
    public static int getYYYYMM(LocalDateTime localDateTime) {
        if (localDateTime == null) {
            localDateTime = LocalDateTime.now();
        }
        int year = localDateTime.getYear();
        int month = localDateTime.getMonth().getValue();
        return year * 100 + month;
    }

    /**
     * 把时间转成年月日小时
     */
    public static int getyyyyMMddHH(LocalDateTime localDateTime) {
        if (localDateTime == null) {
            localDateTime = LocalDateTime.now();
        }
        int yearMonth = getYYYYMM(localDateTime);
        int day = localDateTime.getDayOfMonth();
        int hour = localDateTime.getHour();
        return yearMonth * 10000 + day * 100 + hour;
    }

    /**
     * 把时间转成年月日
     */
    public static int getYyyyMMdd(LocalDateTime localDateTime) {
        if (localDateTime == null) {
            localDateTime = LocalDateTime.now();
        }
        int year = localDateTime.getYear();
        int month = localDateTime.getMonth().getValue();
        int day = localDateTime.getDayOfMonth();
        return year * 10000 + month * 100 + day;
    }

    /**
     * 计算两个时间之间的时间差,最新的时间放在后面
     */
    public static int getMinutes(LocalDateTime startTime, LocalDateTime endTime) {
        Duration duration = Duration.between(startTime, endTime);
        long days = duration.toDays();
        long hours = duration.toHours();
        long minutes = duration.toMinutes();
        int minutesInt = Long.valueOf(minutes).intValue();
        // long seconds = duration.toSeconds();
        long millis = duration.toMillis();
        long nanos = duration.toNanos();

        System.out.println("相差天数：" + days);
        System.out.println("相差小时数：" + hours);
        System.out.println("相差分钟数：" + minutes);
        System.out.println("相差毫秒数：" + millis);
        System.out.println("相差纳秒数：" + nanos);
        return minutesInt;
    }
    //最新的时间放在后面
    public static int getHours(LocalDateTime startTime, LocalDateTime endTime) {
        Duration duration = Duration.between(startTime, endTime);
        long days = duration.toDays();
        long hours = duration.toHours();
        long minutes = duration.toMinutes();
        int hoursInt = Long.valueOf(hours).intValue();
        // long seconds = duration.toSeconds();
        long millis = duration.toMillis();
        long nanos = duration.toNanos();

        System.out.println("相差天数：" + days);
        System.out.println("相差小时数：" + hours);
        System.out.println("相差分钟数：" + minutes);
        System.out.println("相差毫秒数：" + millis);
        System.out.println("相差纳秒数：" + nanos);
        return hoursInt;
    }

    public static void main(String[] args) throws ParseException {
//        System.out.println(String2LocalTime("21:00"));
//        System.out.println(String2LocalTime("21qweqwe"));

//        System.out.println(getYYYYMM(null));

//        String as = "aaa.";
//        as = as.substring(0, as.indexOf("."));
//        System.out.println(as);
//
//        System.out.println(formatToString(LocalDateTime.now(),FORMAT_SMS));
//        System.out.println(formatToString(LocalDateTime.now(),FORMAT_SN));
//        System.out.println(formatToString(LocalDateTime.now(),FORMAT_SN));

//        System.out.println(getYyyyMMdd(null));
//
//        System.out.println(formatStringToLocalDateTime("20230524224815" ,FORMAT_SMS));

        getMinutes(LocalDateTime.now(), LocalDateTime.now().plusMinutes(5));

        System.out.println(getyyyyMMddHH(null));
        //2023-08-09T15:50:09.759
        LocalDateTime beginTime1 = DateTimeUtil.formatStringToLocalDateTime("2023-08-09 15:50:09.759", FORMAT_DATE_SSS);
        System.out.println(beginTime1);
        System.out.println("2023-08-09 15:50:09.759".length());

        LocalDateTime beginTime2 = DateTimeUtil.formatStringToLocalDateTime("2023-08-09 15:50", FORMAT_DATE_yyyyMMddHHmm);
        System.out.println(beginTime2);
        System.out.println("2023-08-09 15:50".length());
        System.out.println("2023-08-09 15:50:00".length());

    }


}
